import pyglet
from bird import Bird
from ground import Ground
from pipeA import PipeA, PipeB
import random
from utils import BitImage
import cv2
import numpy as np


def center_image(image):
    """Sets an image's anchor point to its center"""
    image.anchor_x = image.width // 2
    image.anchor_y = image.height // 2


game_window = pyglet.window.Window(800, 800)

pyglet.resource.path = ['./resource/']
pyglet.resource.reindex()
main_batch = pyglet.graphics.Batch()

player_image = pyglet.resource.image("1.png")
ground_image = pyglet.resource.image("ground.png")
pipeA_image = pyglet.resource.image("pipeA.png")
pipeB_image = pyglet.resource.image("pipeB.png")


grounds = [Ground(ground_image, batch=main_batch, x=x * 37) for x in range(23)]
pipeA = [PipeA(pipeA_image, x=800 + x * 500, batch=main_batch) for x in range(3)]
pipeB = [PipeB(pipeB_image, x=800 + x * 500, batch=main_batch) for x in range(3)]
center_image(player_image)
bird = Bird(img=player_image, x=0, y=0, batch=main_batch)
game_window.push_handlers(bird)
score_label = pyglet.text.Label(text="0", x=0, y=400, batch=main_batch)

bird_bit = BitImage("resource/1.png", 28 + 1, 28, 15, 15 + 1)
pipeA_bit = BitImage("resource/pipeA.png")
pipeB_bit = BitImage("resource/pipeB.png")

die_sound = pyglet.resource.media("die.wav", streaming=False)
hit_sound = pyglet.resource.media("hit.wav", streaming=False)
point_sound = pyglet.resource.media("point.wav", streaming=False)
swooshing_sound = pyglet.resource.media("swooshing.wav", streaming=False)

pyglet.media.synthesis.Silence(0.5).play()




@game_window.event
def on_draw():
    # draw things here
    game_window.clear()
    main_batch.draw()


def update(t):
    check()
    bird.update(t)
    for ground in grounds:
        ground.update(t)
    for i in range(3):
        pipeA[i].update(t)
        pipeB[i].update(t)
        if pipeA[i].new:
            pipeA[i].new = False
            r = random.randrange(150, 600)
            pipeA[i].y = r - pipeA_image.height
            pipeB[i].y = r + 250


def get_intersection(x1, y1, x2, y2, x3, y3, x4, y4):
    # get intersection points of two rect
    # https://stackoverflow.com/questions/19753134/get-the-points-of-intersection-from-2-rectangles
    x5 = max(x1, x3)
    y5 = max(y1, y3)
    x6 = min(x2, x4)
    y6 = min(y2, y4)
    return x5, y5, x6, y6


def check():
    dis = [abs(pipeA[i].x + 0.5 * pipeA[i].width - bird.x) for i in range(3)]
    i = dis.index(min(dis))

    score_label.text = str(dis.index(min(dis)))
    if bird.y < (pipeA[i].y + pipeA_image.height + pipeB[i].y) // 2:
        x1, y1, x2, y2 = get_intersection(pipeA[i].x, pipeA[i].y,
                                          pipeA[i].x + pipeA[i].width - 1,
                                          pipeA[i].y + pipeA[i].height - 1,
                                          bird.x - 60,
                                          bird.y - 60,
                                          bird.x + 60,
                                          bird.y + 60)
    else:
        x1, y1, x2, y2 = get_intersection(pipeB[i].x, pipeB[i].y,
                                          pipeB[i].x + pipeB[i].width - 1,
                                          pipeB[i].y + pipeB[i].height - 1,
                                          bird.x - 60,
                                          bird.y - 60,
                                          bird.x + 60,
                                          bird.y + 60)
    if x1 < x2 and y1 < y2:  # two rectangles intersected
        cut = bird_bit.get_img(-bird.rotation)[  # openCV's direction of rotation is opposite from pyglet
              int(bird_bit.height - 1 - (y2 - (bird.y - 60))):int(bird_bit.height - 1 - (y1 - (bird.y - 60))),
              int(x1 - (bird.x - 60)):int(x2 - (bird.x - 60))]

        if cut.shape[0] > 0 and cut.shape[1] > 0 and np.max(cut) == 255:
            if bird._die is False:
                die_sound.play()
                # player.queue(die)
                bird.die()
            print("hit")



if __name__ == '__main__':
    pyglet.clock.schedule_interval(update, 1 / 120.0)
    pyglet.app.run()
